package test;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;

import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;

import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TopFieldDocs;
import org.apache.lucene.search.TopScoreDocCollector;

import org.apache.lucene.store.FSDirectory;

import org.apache.lucene.util.Version;

import java.io.File;
import java.io.IOException;

public class HelloLucene {
	public static void main(String[] args) throws IOException, ParseException {
		// 0. Specify the analyzer for tokenizing text.
		// The same analyzer should be used for indexing and searching
		StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_35);

		// 1. create the index
		FSDirectory index = FSDirectory.open(new File("index"));

		IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_35,
				analyzer);

		IndexWriter w = new IndexWriter(index, config);
		addDoc(w, "Cứt chó a3", 1);
		addDoc(w, "Cứt chó a4", 2);
		addDoc(w, "Lucene for Dummies", 5);
		addDoc(w, "Managing Gigabytes", 3);
		addDoc(w, "The Art of Computer Science", 10);
		addDoc(w, "Cứt chó a2", 7);
		addDoc(w, "Cứt chó a1", 6);
		w.close();

		// 2. query
		String querystr = args.length > 0 ? args[0] : "cứt chó ";

		// the "title" arg specifies the default field to use
		// when no field is explicitly specified in the query.
		Query q = new QueryParser(Version.LUCENE_35, "title", analyzer)
				.parse(querystr);

		// 3. search
		int hitsPerPage = 100;
		@SuppressWarnings("deprecation")
		IndexSearcher searcher = new IndexSearcher(index, true);
		TopScoreDocCollector collector = TopScoreDocCollector.create(
				hitsPerPage, true);

		TopFieldDocs dd = searcher.search(q, 10, new Sort(new SortField(
				"count", SortField.STRING, true)));

		ScoreDoc[] hits = dd.scoreDocs;
		collector.getClass();

		// 4. display results
		System.out.println("Found " + hits.length + " hits.");
		for (int i = 0; i < hits.length; ++i) {
			int docId = hits[i].doc;
			Document d = searcher.doc(docId);

			System.out.println((i + 1) + ". " + d.get("title") + " - "
					+ d.get("count"));
		}

		// searcher can only be closed when there
		// is no need to access the documents any more.
		searcher.close();
	}

	private static void addDoc(IndexWriter w, String value, int count)
			throws IOException {
		Document doc = new Document();
		doc.add(new Field("title", value, Field.Store.YES, Field.Index.ANALYZED));
		doc.add(new Field("count", Integer.toString(count), Field.Store.YES,
				Field.Index.NOT_ANALYZED));
		w.addDocument(doc);
	}

}
